package main

import (
	"context"
	"fmt"
	"tk-gen/controller"
	"tk-gen/types"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

// Schema returns a list of schemas
func (a *App) Schema(dsn string) ([]types.Schema, error) {
	data, err := controller.Schema(dsn)
	if err != nil {
		Alert(a.ctx, err.Error())
		return nil, err
	}
	return data, nil
}

// Query returns a query for the given name
func (a *App) Query(dsn string, query string, rows bool) ([]types.Query, error) {
	data, err := controller.Query(dsn, query, rows)
	if err != nil {
		Alert(a.ctx, err.Error())
		return nil, err
	}
	return data, nil
}
func (a *App) TreeFile() ([]types.FileTree, error) {
	data, err := controller.TreeFile()
	if err != nil {
		Alert(a.ctx, err.Error())
		return nil, err
	}
	return data, nil
}
func (a *App) CreateFile(filename string) error {
	err := controller.CreateFile(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) CreateDir(filename string) error {
	err := controller.CreateDir(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) CopyFile(filename string) error {
	err := controller.CopyFile(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) CopyDir(filename string) error {
	err := controller.CopyDir(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) ReadFile(filename string) (string, error) {
	content, err := controller.ReadFile(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return "", err
	}
	return content, nil
}
func (a *App) WriteFile(filename string, content string) error {
	err := controller.WriteFile(filename, content)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) RenameFile(oldpath string, newpath string) error {
	err := controller.RenameFile(oldpath, newpath)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func (a *App) RemoveFile(filename string) error {
	err := controller.RemoveFile(filename)
	if err != nil {
		Alert(a.ctx, err.Error())
		return err
	}
	return nil
}
func Alert(ctx context.Context, message string) {
	runtime.MessageDialog(ctx, runtime.MessageDialogOptions{
		Type:    runtime.InfoDialog,
		Title:   "消息提示",
		Message: message,
		Buttons: []string{"确定"},
	})
}
